//
//  Language.m
//  TownCenterProject
//
//  Created by ASAL on 7/5/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Language.h"

#define BaseBundle  @"MooreDollString"

@implementation Language

//1）創建靜態變量bundle，以及獲取方法bundle（註：此處不要使用getBundle）。
static NSBundle *bundle = nil;

+ ( NSBundle * )bundle{
    
    return bundle;
    
}
//初始化方法：
//userLanguage儲存在NSUserDefaults中，首次加載時要檢測是否存在，如果不存在的話讀AppleLanguages，並賦值給userLanguage。
+(void)initUserLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [def valueForKey:@"userLanguage"];
    
    if(string.length == 0){
        
        //獲取系統當前語言版本(中文zh-Hans,英文en)
        
        NSArray* languages = [def objectForKey:@"AppleLanguages"];
        
        NSString *current = [languages objectAtIndex:0];
        
        string = current;
        
        [def setValue:current forKey:@"userLanguage"];
        
        [def synchronize];//持久化，不加的話不會保存
    }
    
    NSLog(@"%@",string);
    //獲取文件路徑
    [self setUserlanguage:string];
}


//3）獲得當前語言方法
+(NSString *)userLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *language = [def valueForKey:@"userLanguage"];
    
    return language;
}

//4）設置語言方法
+(void)setUserlanguage:(NSString *)language{
    
    if (!language) {
        return;
    }
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    //1.第一步改變bundle的值
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj" ];
    
    bundle = [NSBundle bundleWithPath:path];
    
    //2.持久化
    [def setValue:language forKey:@"userLanguage"];
    
    [def synchronize];
}

+(UIStoryboard *)locatizedStoryboardWithName:(NSString *)storyBoardName{
    UIStoryboard *storyboard = [UIStoryboard   storyboardWithName:storyBoardName bundle:bundle];
    return storyboard ;

}
+(NSString *)get:(NSString *)key alter:(NSString *)alternate {
    return [bundle localizedStringForKey:key value:alternate table:BaseBundle];
}

//[_imageView setImage:[UIImage imageWithContentsOfFile:[Language getImagePath:@"abc" WithExtension:@"png"]]];
+(NSString *)getImagePath:(NSString *)key WithExtension:(NSString *)extension{
    
    return [bundle pathForResource:key ofType:extension];
}
@end
